package com.zgkxzx.mvpbase.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;

import com.zgkxzx.mvpbase.presenter.BasePresenter;
import com.zgkxzx.mvpbase.utils.ActivityUtil;
import com.zhy.autolayout.AutoLayoutActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @创建者: zgkxzx
 * @创建时间: 2016-11-10
 * @描述: 基类Activity, 每个Activity进行继承
 */
public abstract class BaseActivity<V, P extends BasePresenter<V>> extends AutoLayoutActivity {

    protected Context mContext;
    protected P presenter;

    private Unbinder bind;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        ActivityUtil.addActivity(this);
        setContentView(getLayoutId());
        bind = ButterKnife.bind(this);
        initVariables();
        initViews(savedInstanceState);
        initData();

        presenter = getPresenter();



        if (presenter != null)
            presenter.attachView((V) this);
    }

    /**
     * 获取布局资源
     * @return 布局资源Id
     */
    protected abstract int getLayoutId();


    /**
     * 初始化参数
     */
    protected abstract void initVariables();


    /**
     * 初始化视图
     * @param savedInstanceState
     */
    protected abstract void initViews(Bundle savedInstanceState);


    /**
     * 载入数据
     */
    protected abstract void initData();


    /**
     * 获取Presenter
     * @return P
     */
    protected abstract P getPresenter();


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null)
            presenter.detachView();
        bind.unbind();
        ActivityUtil.removeActivity(this);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}